package com.rs.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.rs.config.BusinessException;
import com.rs.entity.Class;
import com.rs.entity.ExamWork;
import com.rs.entity.Response;
import com.rs.entity.Student;
import com.rs.entity.excel.StudentExcelEntity;
import com.rs.entity.login.Menu;
import com.rs.entity.login.User;
import com.rs.service.ClassService;
import com.rs.service.ExamWorkService;
import com.rs.service.StudentLoginService;
import com.rs.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dehang
 * @date 2019/6/1
 */
@Controller
@RequestMapping("/stu")
public class StudentLoginController {

    @Autowired
    private StudentLoginService studentLoginService;
    @Autowired
    private ExamWorkService examWorkService;
    @Autowired
    private ClassService classService;
    @Autowired
    private StudentService studentService;
    
    @RequestMapping("/login")
    public String getTestById() {
        return "student/stu/login";
    }

    /**
     * 验证账号密码
     * @param username
     * @param httpSession
     * @return
     */
    @RequestMapping(value="/dologin",method = RequestMethod.POST)
    @ResponseBody
    public Map dologin(String username, HttpSession httpSession){
        Map result = new HashMap();
        Student user = null;
        try {
            user = studentLoginService.login(username);
        } catch (BusinessException e) {
            result.put("code", 1);
            result.put("msg", e.getMessage());
            return result;
        } catch (Exception e) {
            result.put("msg", "系统错误");
            return result;
        }
        if (user == null) {
            result.put("code", 1);
            result.put("msg", "账号或密码错误");
        } else {
            result.put("code", 0);
            httpSession.setAttribute("stuuser",user);

        }
        return result;
    }

    /**
     * 从本系统登陆首页
     * @param httpSession
     * @param model
     * @return
     */
    @RequestMapping("/index")
    public String index(HttpSession httpSession, Model model){
        Object user = httpSession.getAttribute("stuuser");
        Student student = (Student)user;
        // 从登录信息中获取用户学号
        String studentNo = student.getStudentNo();
        // 根据学号查询 examwork。
        List<ExamWork> zuoye = examWorkService.getInfoByStudentNoAndType(studentNo, 1);
        for (ExamWork ew:zuoye){
            if(ew.getBeforeSize()==0){
                ew.setTypeShow("<span style='color:red'>未完成</span>");
            }else{
                ew.setTypeShow("<span style='color:blue'>已提交</span>");
            }
        }
        List<ExamWork> kaoshi = examWorkService.getInfoByStudentNoAndType(studentNo, 2);
        for (ExamWork ew:kaoshi){
            if(ew.getBeforeSize()==0){
                ew.setTypeShow("<span style='color:red'>未完成</span>");
            }else{
                ew.setTypeShow("<span style='color:blue'>已提交</span>");
            }
        }
        model.addAttribute("stu",student);
        model.addAttribute("zuoye",zuoye);
        model.addAttribute("kaoshi",kaoshi);
        return "student/stu/index";
    }
    
    
    @RequestMapping("/uploadStudents")
    @ResponseBody
    public Response<Boolean> test(@RequestParam("file") MultipartFile multipartFile) throws Exception {
        ImportParams params = new ImportParams();
        List<StudentExcelEntity> list = ExcelImportUtil.importExcel(multipartFile.getInputStream(), StudentExcelEntity.class, params);
        studentService.uploadSave(list);
        return Response.success(Boolean.TRUE);
    }
    
    
    @RequestMapping("/getExamWork")
    @ResponseBody
    public Response getExamWork(HttpServletRequest request, Integer type) throws Exception {

        Object user = request.getSession().getAttribute("stuuser");
        if (user == null || !(user instanceof Student)) {
            return Response.fail("无权限");
        }
        Student student = (Student)user;
        ImportParams params = new ImportParams();
        // 从登录信息中获取用户学号
        String studentNo = student.getStudentNo();
        
        // 根据学号查询 examwork。
        List<ExamWork> examWorks = examWorkService.getInfoByStudentNoAndType(studentNo, type);

//        List<StudentExcelEntity> list = ExcelImportUtil.importExcel(multipartFile.getInputStream(), StudentExcelEntity.class, params);
//        studentService.uploadSave(list);
        return Response.success(examWorks);
    }
    
    
    @RequestMapping("/selectExam")
    public String selectExam(HttpServletRequest request,Model model ,Integer id){

        try {
            //查询当前考试
            ExamWork examWork=examWorkService.getOne(id);
            //查询文件url地址
            Student student = (Student)request.getSession().getAttribute("stuuser");
            String url=examWorkService.getDownUrl(id,student.getStudentNo());
            model.addAttribute("exam",examWork);
            model.addAttribute("url",url);
            model.addAttribute("stu",student);
            model.addAttribute("time",CalTime(examWork.getEndTime(),examWork.getStartTime()));
            model.addAttribute("miao",CalTime(examWork.getEndTime(),DateUtil.now())*60);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "student/stu/exam";
    }

    // 计算两个时间差，返回为分钟。
    private  long CalTime(String time1, String time2) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        long minutes = 0L;
        try {
            Date d1 = df.parse(time1);
            Date d2 = df.parse(time2);
            long diff = d1.getTime() - d2.getTime();// 这样得到的差值是微秒级别
            minutes = diff / (1000 * 60);
            if(minutes<0){
                minutes=0;
            }
        } catch (ParseException e) {
            System.out.println("抱歉，时间日期解析出错。");
        }
        return minutes;
    }
    
    /**
     * 上传作业
     * @param request
     * @param file
     * @return
     * @throws IOException
     */
    @RequestMapping("/uploadWork")
    @ResponseBody
    public Response<String> uploadWork(HttpServletRequest request,
                                       @RequestParam("file") MultipartFile file,
                                       @RequestParam("examId") Integer examId) throws IOException {

        ExamWork one = examWorkService.getOne(examId);
        if (one != null) {
            String endTime = one.getEndTime();
            DateTime parse = DateUtil.parse(endTime);
            if (new Date().getTime() > parse.getTime()) {
                return Response.fail("已结束，无法提交！");
            }
        }

        Student student = (Student)request.getSession().getAttribute("stuuser");
        // 获取课程编号
        String classNo = getClassNo(examId);
        // 目录：课程编号+考试id
        // 文件名：课程编号+考试id+学号.rar/zip
        // 业务文件存储路径
        String businessFilePath = classNo+"_"+examId;
        //根据考试id加学生编号查询出试卷名称
        String sjname=examWorkService.getDownUrlName(examId,student.getStudentNo());
        int sjnameindex = 0;
        String sjnameindexffix = "";
        if(sjname!=null){
            sjnameindex =  sjname.indexOf(".");
            sjnameindexffix = sjname.substring(0,sjnameindex);
        }

        if(!file.isEmpty()){
            //可以对user做一些操作如存入数据库
            //以下的代码是将文件file重新命名并存入Tomcat的webapps目录下项目的下级目录fileDir
            String fileRealName = file.getOriginalFilename();                   //获得原始文件名;
            int pointIndex =  fileRealName.indexOf(".");                        //点号的位置
            String fileSuffix = fileRealName.substring(pointIndex);             //截取文件后缀

            String realPath = request.getSession().getServletContext().getRealPath(""); //获取服务器指定文件存取路径
            System.err.println(realPath);
            String savePath = realPath+"/upload/"+businessFilePath;
            String saveName = businessFilePath+"_"+student.getStudentNo()+"_"+sjnameindexffix+fileSuffix;
            String resultPath = "/upload/"+businessFilePath+"/"+businessFilePath+"_"+student.getStudentNo()+"_"+sjnameindexffix+fileSuffix;
            
            File file1 = new File(savePath);
            if (!file1.exists()) {
                file1.mkdirs();
            }
            
            File savedFile = new File(savePath, saveName);
            boolean isCreateSuccess = savedFile.createNewFile();
            if(isCreateSuccess){
                file.transferTo(savedFile);  //转存文件
            }
            examWorkService.updateLoginStatus(examId, student.getStudentNo(),resultPath);
            return Response.success(resultPath);
        }
        return Response.fail("上传失败！");
    }
    
    /**
     * 校验作业密码
     * @return
     * @throws IOException
     */
    @RequestMapping("/verifyPassword")
    @ResponseBody
    public Response<String> verifyPassword(HttpServletRequest request, @RequestParam("id") Integer examId, @RequestParam("password") String password) throws IOException {
        Student student = (Student)request.getSession().getAttribute("stuuser");
        String ip = getIp(request);
        ExamWork one = examWorkService.getOne(examId);
        if (one != null && one.getRemark3().equals(password)) {
            examWorkService.updateLoginInfo(examId, student.getStudentNo(), ip);
            return Response.success("成功");
        }
        return Response.fail("密码错误");
    }
    
    
    
    /**
     * 获取用户ip地址
     * @return
     */
    public static String getIp(HttpServletRequest request){
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    
    
    /**
     * 根据考试id获取课程编号
     * @param examId
     * @return
     */
    private String getClassNo(Integer examId) {
        // examId 查询 考试表 remark1（课程id）
        ExamWork one = examWorkService.getOne(examId);
        // 课程id
        String classId = one.getRemark1();
        // 根据课程id，查询class表 remark字段 得到课程编号。
        Class aClass = classService.getOne(Integer.valueOf(classId));
        // 课程编号
        String remark = aClass.getRemark();
        
        return remark;
    }


    @RequestMapping("/redirect")
    public String redirect(HttpServletRequest request, HttpServletResponse response) throws Exception{
        //清理本地session
        request.getSession().removeAttribute("stuuser");
        //重定向登陆页
        return "redirect:/stu/login";
    }
}
